package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.executer.AbstractExecuter;
import com.qdlc.p2p.biz.executer.ExecuterHelper;
import com.qdlc.p2p.biz.executer.impl.ScoreLotteryMoneyExecuter;
import com.qdlc.p2p.biz.log.score.BaseScoreLog;
import com.qdlc.p2p.biz.log.score.lottery.ScoreLotteryLog;
import com.qdlc.p2p.biz.log.score.lottery.ScoreLotteryWinningLog;
import com.qdlc.p2p.biz.service.ScoreLotteryRecordService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.ScoreTemplateConstant;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.ScoreDao;
import com.qdlc.p2p.dal.dao.ScoreLotteryDao;
import com.qdlc.p2p.dal.dao.ScoreLotteryRecordDao;
import com.qdlc.p2p.dal.dao.ScoreTypeDao;
import com.qdlc.p2p.dal.dto.Score;
import com.qdlc.p2p.dal.dto.ScoreLottery;
import com.qdlc.p2p.dal.dto.ScoreLotteryRecord;
import com.qdlc.p2p.dal.dto.Tpp;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.ScoreLotteryModel;
import com.qdlc.p2p.dal.model.ScoreLotteryRecordModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

@Service("scoreLotteryRecordService")
public class ScoreLotteryRecordServiceImpl implements ScoreLotteryRecordService {

    @Resource
    private ScoreDao scoreDao;

    @Resource
    private ScoreTypeDao scoreTypeDao;

    @Resource
    private ScoreLotteryDao scoreLotteryDao;

    @Resource
    private ScoreLotteryRecordDao scoreLotteryRecordDao;

    @Override
    public double lottery(ScoreLotteryRecordModel model) {
        long userId = model.getUser().getUserId();
        Score userScore = scoreDao.findByUserId(userId);//获取积分信息
        int score = scoreTypeDao.getScoreTypeByNid(ScoreTemplateConstant.SCORE_LOTTERY).getValue();
        if (userScore.getValidScore() < score) {
            throw new UserException("您当前可用积分不足!", BusinessException.TYPE_JSON);
        }
        List<ScoreLottery> list = scoreLotteryDao.getAllLottery();
        // 随机数最大范围
        int range = 10000;
        // 抽中对象
        ScoreLottery scoreLottery = null;
        // 抽中结果名称
        String name = null;
        Random r = new Random();
        // 中奖率
        double rate = list.get(0).getRate();
        // 产生随机数
        int round = r.nextInt(range);
        // 抽中结果值
        double result = -round % 2;
        for (int i = 0; i < list.size(); i++) {
            if (round < rate * range / 100) {
                scoreLottery = list.get(i);
                name = scoreLottery.getName();
                result = scoreLottery.getId();
                break;
            }
            if (i != list.size() - 1) {
                rate = BigDecimalUtil.add(rate, list.get(i + 1).getRate());
            }
        }

        //会员积分记录信息 更新积分， 更新日志信息
        Global.setTransfer("score", score);
        Global.setTransfer("name", name);
        BaseScoreLog bLog = new ScoreLotteryLog(userId, score);
        bLog.doEvent();
        if (scoreLottery != null) {
            ScoreLotteryRecord scoreLotteryRecord = new ScoreLotteryRecord();
            scoreLotteryRecord.setUser(model.getUser());

            scoreLotteryRecord.setType(scoreLottery.getType());
            scoreLotteryRecord.setValue(scoreLottery.getValue());

            scoreLotteryRecord.setAddTime(DateUtil.getNow());
            scoreLotteryRecord.setAddIp(Global.getIP());
            scoreLotteryRecordDao.save(scoreLotteryRecord);

            if (scoreLottery.getType() == ScoreLotteryModel.TYPE_SCORE) {
                //会员积分记录信息 更新积分， 更新日志信息
                Global.setTransfer("score", scoreLottery.getValue());
                bLog = new ScoreLotteryWinningLog(userId, (int) scoreLottery.getValue());
                bLog.doEvent();
            } else if (scoreLottery.getType() == ScoreLotteryModel.TYPE_MONEY) {
                //抽中现金
                double money = scoreLottery.getValue();
                Global.setTransfer("money", money);
                Global.setTransfer("user", model.getUser());
                AbstractExecuter scoreLotteryMoneyExecuter = ExecuterHelper.getExecuter(ScoreLotteryMoneyExecuter.class);
                scoreLotteryMoneyExecuter.execute(money, model.getUser(), new User(SystemConfigs.ADMIN_ID));

                Tpp tpp = new Tpp(TppModel.SCORE_LOTTERY_MONEY, TppModel.TPP_TRANSFER, null, model.getUser(), money, null);
                tpp.setTppUserCustId(SystemConfigHelper.getValue(Nid.MERCHANT_ID));
                tpp.setTppBorrowId(TppModel.SCORE_LOTTERY_MONEY_NAME);
                TppModel tppModel = TppModel.instance(tpp);
                TppBaseInterface tppService = TppServiceFactory.newIntance();
                tppService.tppTransfer(tppModel);
            }
        }
        return result;
    }

    @Override
    public List<ScoreLotteryRecordModel> getNewList() {
        QueryParam param = QueryParam.getInstance();
        param.addOrder(OrderType.DESC, "id");
        List<ScoreLotteryRecord> list = scoreLotteryRecordDao.findByCriteria(param, 0, ScoreLotteryRecordModel.SCORELOTTERYRECORD_NEWLIST_SIZE);
        List<ScoreLotteryRecordModel> modelList = new ArrayList<ScoreLotteryRecordModel>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ScoreLotteryRecord item = list.get(i);
                ScoreLotteryRecordModel model = new ScoreLotteryRecordModel();
                model.setUserName(item.getUser().getHideUserName());
                model.setType(item.getType());
                model.setValue(item.getValue());
                modelList.add(model);
            }
        }
        return modelList;
    }

    @Override
    public PageDataList<ScoreLotteryRecordModel> findPageList(ScoreLotteryRecordModel model) {
        return scoreLotteryRecordDao.findPageList(model);
    }
}
